ssize_t recv_message(int sockfd, protocol_header_t *header)
{
    ssize_t total_received = 0;
    while (total_received < sizeof(protocol_header_t))
    {
        ssize_t bytes_received = recv(sockfd, ((char *)&header) + total_received, sizeof(protocol_header_t) - total_received, 0);
        if (bytes_received <= 0)
        {
            if (bytes_received == 0) // Connection closed by peer
            {
                fprintf(stderr, "Connection closed by peer during header recv.\n");
                return ERR_CONNECTION_ERROR;
            }
            else // bytes_received == -1
            {
                if (errno == EINTR)
                {
                    continue;
                }
                if (errno == EAGAIN || errno == EWOULDBLOCK)
                {
                    // Non-blocking socket, no data available right now for a new header
                    return ERR_RECV_WOULD_BLOCK;
                }
                perror("recv header failed");
                return ERR_CONNECTION_ERROR;
            }
        }
        total_received += bytes_received;
    }
    return total_received;
}